Autocomplete/ Autosuggest is a feature provided by many web browsers, e-mail programs, search engine interfaces, source code editors, database query tools, word processors, and command line interpreters. Autocomplete involves the program predicting a word or phrase that the user wants to type in without the user actually typing it in completely.
Here i am going to demonstrate a simple example of autosuggest. Thi is based on php and ajax. It will fetch country names based on the keyword entered in textbox from the database. We will create three files for this:-
1. First Step :- Make a HTML file containing the textbox
Keyword: <input type="text" id="keyword" name="keyword" onKeyUp="dowork();"> <div id="ajax_result" style="display:none; width:200px;"></div>
2. Second step:- Create a js file
function getHttp(){ var xmlhttp try{ xmlhttp=new XMLHttpRequest(); }catch(e){ try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ xmlhttp=new ActiveXOject("Microsoft.XMLHTTP"); }catch(e){ alert("Your browser doesnt support Ajax."); return false; } } } return xmlhttp; } //create request function dowork(){ var keyword = document.getElementById('keyword').value; document.getElementById("ajax_result").style.display="block"; document.getElementById("ajax_result").innerHTML= '<img src="images/loading.gif" />'; xmlhttp=getHttp(); if(xmlhttp){ xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4){ document.getElementById("ajax_result").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax_server.php?keyword="+keyword, true); xmlhttp.send(null); } }
2. Third step:- Create a php file, which will fetch country name based on keyword from db.
';
while($row = mysql_fetch_array($result))
{
$str = strtolower($row['name']);
$start = strpos($str,$keyword);
$end = similar_text($str,$keyword);
$last = substr($str,$end,strlen($str));
$first = substr($str,$start,$end);
$final = '<span class="bold">'.$first.'</span>'.$last;
echo '
'.$final.''; } echo ""; } else echo "No Result"; } ?>